package com.myslef.teaching_platfrom.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.myslef.teaching_platfrom.common.R;
import com.myslef.teaching_platfrom.domain.course.Course;
import com.myslef.teaching_platfrom.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.List;

@RestController
@RequestMapping("/course")
@CrossOrigin(origins = "http://localhost:8080")
public class CourseController {
    @Autowired
    private CourseService courseService;

    @Value("${upload.dir}") // 读取配置文件中的上传文件保存目录
    private String uploadDir;

    @GetMapping
    public R getCourse(){
        List<Course> courseList = courseService.list();
        return R.success(courseList);
    }
    @GetMapping("/{id}")
    public R getCourse(@PathVariable Integer id){
        Course course = courseService.getById(id);
        return R.success(course);
    }



    @PostMapping("/upload/{id}")
    public R uploadImage(@PathVariable Integer id, @RequestParam(value = "courseName") String courseName,
                         @RequestParam(value = "file", required = false) MultipartFile file,
                         @RequestParam(value = "className")String className,
                         @RequestParam(value = "teacherName") String teacherName)
    {
        Long now = System.currentTimeMillis();

        Course course = new Course();
        course.setCourseName(courseName);
        course.setSchoolName("安徽师范大学");
        course.setTeacherId(id);
        course.setClassName(className);
        course.setStudentCount(0);
        course.setStatus(0);
        course.setTeacherName(teacherName);
        course.setCreateTime(new Timestamp(now));
        if(file!=null){
            try {
                // 获取上传的文件名和文件扩展名
                String originalFileName = file.getOriginalFilename();
                String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
                System.out.println(originalFileName +"," + fileExtension);
                // 生成新的文件名
                String newFileName =id.toString()+"_course_" + now + "." + fileExtension;

                // 创建上传目录
                Path uploadPath = Paths.get(uploadDir+"/course");
                if (!Files.exists(uploadPath)) {
                    try {
                        Files.createDirectories(uploadPath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 保存上传的文件
                Path filePath = Paths.get(uploadDir+"/course", newFileName);
                Files.write(filePath, file.getBytes());

                course.setPicUrl(filePath.toString());
                System.out.println(filePath);

            } catch (IOException e) {
                // 返回上传失败信息
                return R.error("上传失败：" + e.getMessage());
            }
        }
        else{
            course.setPicUrl(uploadDir+"course/init.jpg");
        }
        courseService.save(course);
        return R.success("创建成功");
    }

    @PostMapping("/uploadIcon/{id}")
    public R uploadImage(@PathVariable Integer id, @RequestParam("file") MultipartFile file) {
        try {
            // 获取上传的文件名和文件扩展名
            String originalFileName = file.getOriginalFilename();
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
            System.out.println(originalFileName +"," + fileExtension);
            // 生成新的文件名
            String newFileName =id.toString()+"_" + System.currentTimeMillis() + "." + fileExtension;

            // 创建上传目录
            Path uploadPath = Paths.get(uploadDir+"/course");
            if (!Files.exists(uploadPath)) {
                try {
                    Files.createDirectories(uploadPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 保存上传的文件
            Path filePath = Paths.get(uploadDir+"/course", newFileName);
            Files.write(filePath, file.getBytes());

            LambdaUpdateWrapper<Course> updateWrapper= new LambdaUpdateWrapper<>();
            updateWrapper.eq(Course::getId, id).set(Course::getPicUrl, filePath.toString());
            courseService.update(updateWrapper);
            System.out.println(filePath);

            // 返回上传成功信息
            return R.success("上传成功！");
        } catch (IOException e) {
            // 返回上传失败信息
            return R.error("上传失败：" + e.getMessage());
        }
    }



    @GetMapping("/image/{id}")
    public ResponseEntity<byte[]> getImage(@PathVariable Integer id) throws IOException {
        // 从数据库中获取图片路径
        LambdaQueryWrapper<Course> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Course::getPicUrl).eq(Course::getId,id);
        Course course = courseService.getOne(lambdaQueryWrapper);
        // 读取图片文件到内存中
        File file = new File(course.getPicUrl());
        InputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        inputStream.close();
        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        // 返回图片内容给前端
        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }

    @GetMapping("/getInviteId/{id}")
    public R getInviteCode(@PathVariable Integer id){
        Course course = courseService.getById(id);
        String inviteId = course.getInviteId();
        return R.success(inviteId);
    }

    @PostMapping("/update")
    public R update(@RequestBody Course course){
        LambdaUpdateWrapper<Course> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Course::getId, course.getId())
                .set(Course::getCourseName, course.getCourseName())
                .set(Course::getTeacherName, course.getTeacherName())
                .set(Course::getClassName, course.getClassName())
                .set(Course::getStatus, course.getStatus());
        boolean update = courseService.update(updateWrapper);
        if(update == true)
            return R.success("更改成功");
        else
            return R.error("更改失败");
    }


}
